import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 极坐标下弧长计算
def arc_length_polar(r, r_prime, alpha, beta):
    """
    计算极坐标系下曲线的弧长
    r: 极径函数
    r_prime: 极径的导数
    alpha, beta: 角度区间
    """
    def integrand(theta):
        return np.sqrt(r(theta)**2 + r_prime(theta)**2)
    
    length, error = integrate.quad(integrand, alpha, beta)
    return length, error

# 示例：心形线的长度
a = 1  # 心形线参数

def r_cardioid(theta):
    return a * (1 + np.cos(theta))

def r_prime_cardioid(theta):
    return -a * np.sin(theta)

length_cardioid, error_cardioid = arc_length_polar(
    r_cardioid, r_prime_cardioid, 0, 2*np.pi)

print(f"心形线的长度: {length_cardioid:.6f} (理论值: {8*a:.6f})")

# 可视化心形线
theta = np.linspace(0, 2*np.pi, 100)
r_vals = r_cardioid(theta)

# 极坐标转直角坐标
x_vals = r_vals * np.cos(theta)
y_vals = r_vals * np.sin(theta)

plt.figure(figsize=(8, 8))
plt.plot(x_vals, y_vals, 'm-', linewidth=2, label='心形线')
plt.xlabel('x')
plt.ylabel('y')
plt.title('心形线')
plt.grid(True)
plt.axis('equal')
plt.legend()

# 标注弧长
plt.text(0, 0.5, f'弧长 L = {length_cardioid:.4f}', fontsize=12, 
         bbox=dict(boxstyle="round,pad=0.3", facecolor="white", alpha=0.7),
         ha='center')

plt.show()